import React, { useState, useEffect } from 'react';
import { Form, Button, Divider, Input, Select, TreeSelect, DatePicker } from 'antd';
import defaultSetting from '../../../../../../../config/defaultSettings';
import { connect } from 'umi';
import styles from './index.less';
import E from 'wangeditor';
import {
  addCommodity,
  UploadCommodity,
  uploadCommodityStep,
  queryCategory,
} from '../../service';
import { handleData, transTitle } from '@/utils/utils';
const { Option } = Select;
let editor = null;
const Step1 = (props) => {
  const { defaultVal, data, handleCurrent, handleId, CommodityId, reviseState } = props;
  const [content, setContent] = useState('');
  const [guarantee, setGuarantee] = useState(false);
  const [form] = Form.useForm();
  const [expireTime, handleExpireTime] = useState();
  const [category, setCategory] = useState([]);
  const [categoryName, handleCategoryName] = useState();
  const getCategory = () => {
    queryCategory().then((res) => {
      if (res.code === 0) {
        const { data } = res;
        transTitle(data);
        setCategory(data);
      }
    });
  };
  useEffect(() => {
    getCategory();
    editor = new E('#div1');
    editor.config.onchange = (newHtml) => {
      setContent(newHtml);
    };
    editor.config.uploadFileName = 'file';
    editor.config.uploadImgServer = `${defaultSetting.baseUrl}/common/upload?module=edit`;
    editor.config.uploadImgMaxSize = 2 * 1024 * 1024;
    editor.config.uploadImgAccept = [];
    editor.config.uploadImgShowBase64 = true;
    editor.config.uploadImgHeaders = {
      token: sessionStorage.getItem('token'),
      type: 'ADMIN',
    };

    editor.config.uploadImgHooks = {
      // 上传图片之前
      // 图片上传并返回了结果，图片插入已成功
      success: function (xhr) {},
      // 图片上传并返回了结果，但图片插入时出错了
      fail: function (xhr, editor, resData) {},
      // 上传图片出错，一般为 http 请求的错误
      error: function (xhr, editor, resData) {
        return {
          prevent: true,
          msg: '上传错误',
        };
      },
      // 上传图片超时
      timeout: function (xhr) {},
      // 图片上传并返回了结果，想要自己把图片插入到编辑器中
      // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
      customInsert: function (insertImgFn, result) {
        // result 即服务端返回的接口

        // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
        insertImgFn(result.data.url);
      },
    };
    /**一定要创建 */
    editor.create();
    defaultVal ? editor.txt.html(defaultVal.description) : null;
    return () => {
      editor.destroy();
    };
  }, []);
  const { validateFields } = form;
  const onValidateForm = async () => {
    const editHtml = editor.txt.html();
    const values = await validateFields();
    values.type = true;
    values.description = editHtml;
    reviseState ? (values.id = CommodityId) : null;
    return reviseState
      ? UploadCommodity(values).then((res) => {
          if (res.code === 0) {
            handleCurrent(1);
          }
        })
      : addCommodity(values).then((res) => {
          if (res.code === 0) {
            const { data } = res;
            handleId(data);
            uploadCommodityStep(data, 1);
            handleCurrent(1);
          }
        });
  };
  const lableStyle = {
    labelCol: { span: 4 },
    wrapperCol: { span: 24 },
  };
  return (
    <>
      <Form
        form={form}
        layout="inline"
        labelAlign="right"
        className={styles.stepForm}
        hideRequiredMark
        {...lableStyle}

        initialValues={defaultVal ? defaultVal : ''}
      >
        <Form.Item
          style={{margin:"20px"}}
          label="赠品名称"
          name="name"
          rules={[
            {
              required: true,
              message: '名称不能为空',
            },
          ]}
        >
          <Input placeholder="请输入赠品名称" />
        </Form.Item>
        <Form.Item
          style={{margin:"20px"}}
          label="条码编号"
          name="barCode"
          rules={[
            {
              required: true,
              message: '条码号必填',
            },
          ]}
        >
          <Input placeholder="请输入条码号" />
        </Form.Item>
        <Form.Item label="商品描述" name="description" style={{ zIndex: 0,margin:"20px" }}>
          <div id="div1" style={{ maxWidth: 1020, marginLeft: 10 }}></div>
        </Form.Item>
      </Form>

      <div className={styles.bottomBtn}>
        <Button type="primary" onClick={onValidateForm}>
          下一步
        </Button>
      </div>
    </>
  );
};

export default connect(({ commodityManagementAndCommodityCreatingSteps }) => ({
  data: commodityManagementAndCommodityCreatingSteps.step,
}))(Step1);
